package com.bjpowernode.service.impl;

import com.bjpowernode.entity.TUser;
import com.bjpowernode.mapper.TUserMapper;
import com.bjpowernode.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    TUserMapper userMapper;

    /**
     * 该方法是UserDetailsService接口中的抽象方法，该方法会在spring security框架登录的时候调用，
     * 用于根据登录时传过来的用户名加载用户对象的一系列操作
     * @param username
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username)
            throws UsernameNotFoundException {
        //根据用户名查询用户对象
        TUser tuser = userMapper.selectByLoginAct(username);
        if(tuser == null){
            throw new UsernameNotFoundException("登录账号不存在");
        }
        //这个User是security框架中自带的User，是UserDetails的一个实现类,构建一个User对象
        UserDetails userDetails = User.builder().username(tuser.getLoginAct())
                .password(tuser.getLoginPwd())
                //这个设置为true表示账号过期了，后面登录校验时会抛异常，登录失败，这个值默认为false
//                .accountExpired(true)
                //这个authorities是设置当前用户的权限，传递的是一个集合，
                //AuthorityUtils.NO_AUTHORITIES表示没有权限，返回的是一个空集合
                .authorities(AuthorityUtils.NO_AUTHORITIES).build();
        //这里把UserDetails(User)返回给security框架之后，框架会用密码加密器PasswordEncoder
        //对密码进行比较
        return userDetails;
    }
}
